package com.sky.handler;

import com.sky.constant.DuplicateNameMapping;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler
    public Result sqlExceptionHandler(SQLIntegrityConstraintViolationException e){
        String message = e.getMessage();

        String duplicateValue = this.extractDuplicateValue(message);
        String duplicateKey = this.extractKeyName(message);

        String name = DuplicateNameMapping.getName(duplicateKey);
        return Result.error(name +"【"+duplicateValue+"】已存在");
    }

    private String extractKeyName(String message) {
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("for key '(.+)'$");
        java.util.regex.Matcher matcher = pattern.matcher(message);
        return matcher.find() ? matcher.group(1) : null;
    }

    private String extractDuplicateValue(String message) {
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("Duplicate entry '(.+)' for key");
        java.util.regex.Matcher matcher = pattern.matcher(message);
        return matcher.find() ? matcher.group(1) : null;
    }

}